import pygame as pg
from entity import *
import time
import pyaudio,wave
import numpy as np
import time
from wav2txt import get_text

screen_width=1000
screen_height=700

def save_audio(p,frames):
    wf = wave.open('test.wav', 'wb')
    wf.setnchannels(1)
    wf.setsampwidth(p.get_sample_size(pyaudio.paInt16))
    wf.setframerate(16000)
    wf.writeframes(b''.join(frames))
    wf.close()
class MainGame():
    WAVE_OUTPUT_FILENAME = 'test.wav'
    mindb=500#最小声音，比这个音量大就录音，否则延迟0.5s结束
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,channels=1,rate=16000,input=True,frames_per_buffer=1024)
    frames = []
    data=None
    started_record=False
    change_state=False
    window=None
    stick=get_stick()
    stick_rect=stick.get_rect()
    stick_rect.top=200
    stick_rect.left=400
    lignts=get_lights()
    color_list=['r','g','y']
    current_color_index,current_light_size=0,0
    light=lignts[color_list[current_color_index]][current_light_size]
    light_rect=light.get_rect()
    light_rect.top=187
    light_rect.left=220
    can_show_both=True
    def __init__(self) -> None: 
        pass
    def startGame(self):
        pg.display.init()
        MainGame.window=pg.display.set_mode((screen_width,screen_height))
        pg.display.set_caption("声控台灯")
        logo = pg.image.load("asset/logo.png")
        pg.display.set_icon(logo) # 可以填img
        
        while True:
            time.sleep(0.02)
            MainGame.window.fill(pg.Color(0,0,0))
            
            self.getEvent()
            if MainGame.can_show_both:
                MainGame.window.blit(MainGame.stick,MainGame.stick_rect)
                MainGame.window.blit(MainGame.light,MainGame.light_rect)
                MainGame.window.blit(self.getTextSuface("developer:D-Studio"),(380,500))
            pg.display.update()

            MainGame.data = MainGame.stream.read(1024,exception_on_overflow = False)
            audio_data = np.frombuffer(MainGame.data, dtype=np.short)
            sound_size = np.max(audio_data)
            
            if sound_size > MainGame.mindb and not MainGame.started_record:
                MainGame.started_record =True
                start_record_time=time.time()
                print("start")
            if sound_size > MainGame.mindb and MainGame.started_record:
                MainGame.frames.append(MainGame.data)
            if sound_size<MainGame.mindb and MainGame.started_record and not MainGame.change_state:
                sound_start_low_time=time.time()
                MainGame.change_state=True
            if sound_size<MainGame.mindb and MainGame.started_record:
                if MainGame.change_state:
                    now=time.time() 
                    if now-sound_start_low_time>0.2:
                        print(now-start_record_time)
                        save_audio(MainGame.p,MainGame.frames)
                        text=get_text()
                        print(text)
                        self.change_light(text)
                        print("end")
                        MainGame.frames=[]
                        MainGame.started_record=False
                        MainGame.change_state=False
                    else:MainGame.frames.append(MainGame.data)
    def getTextSuface(self,text):
        pg.font.init()
        # print(pg.font.get_fonts())
        font=pg.font.SysFont("simsun",30)
        textSurface=font.render(text,True,pg.Color(0,255,0))
        return textSurface
    def getEvent(self):
        eventList=pg.event.get()
        for event in eventList:
            if event.type==pg.QUIT:
                self.endGame()
    def endGame(self):
        print("欢迎再次使用")
        exit()
    def change_light(self,text):
        if "颜色" in text:
            if MainGame.current_color_index==2:MainGame.current_color_index=0
            else:MainGame.current_color_index+=1
            
            MainGame.light=MainGame.lignts[MainGame.color_list[MainGame.current_color_index]][MainGame.current_light_size]
        if text=="亮一点" or text=="了一点" :
            if MainGame.current_light_size==0:pass
            else:MainGame.current_light_size-=1
            MainGame.light=MainGame.lignts[MainGame.color_list[MainGame.current_color_index]][MainGame.current_light_size]

        if text=="暗一点" or text=="慢一点" or text=="一点"  or text=="而一点" :
            if MainGame.current_light_size==2:pass
            else:MainGame.current_light_size+=1
            MainGame.light=MainGame.lignts[MainGame.color_list[MainGame.current_color_index]][MainGame.current_light_size]
        if "睡觉" in text:
            MainGame.can_show_both=False
        if text=="开灯" or text=="台灯"  or "当" in text  or "等" in text :
            MainGame.can_show_both=True


if __name__=="__main__":
    MainGame().startGame()    
